import { Injectable } from '@nestjs/common';
import * as Minio from 'minio';

@Injectable()
export class MinioService {
  private minioClient: Minio.Client;

  constructor() {
    // 初始化 MinIO 客户端
    this.minioClient = new Minio.Client({
      endPoint: '8.137.123.249', // MinIO 服务器地址
      port: 9000, // MinIO 端口，通常是 9000
      useSSL: false, // 是否启用 SSL
      accessKey: 'lOUpnscQuDpIUvMj7vRj', // MinIO Access Key
      secretKey: 'XWtea3NEhggcOHl0Qv0GvBo65QH4RBBduw37huU6', // MinIO Secret Key
    });
  }

  // 上传文件到 MinIO
  async uploadFile(
    bucketName: string,
    file: Express.Multer.File,
  ): Promise<string> {
    return new Promise(async (resolve, reject) => {
      // const objectName = file.originalname; // 使用文件名作为对象名称/**/
      const objectName = `test/${file.originalname}`; // 构造目录路径 + 文件名
      const meta = {
        'Content-Type': file.mimetype,
      };
      await this.minioClient.putObject(
        bucketName,
        objectName,
        file.buffer,
        file.size,
        meta,
      );
      const url = await this.getFileUrl(bucketName, objectName);
      resolve(url.split('?')[0]);
    });
  }

  // 获取 MinIO 中的文件 URL
  async getFileUrl(bucketName: string, objectName: string): Promise<string> {
    return this.minioClient.presignedGetObject(bucketName, objectName);
  }

  // 检查 MinIO 桶是否存在
  async bucketExists(bucketName: string): Promise<boolean> {
    try {
      const exists = await this.minioClient.bucketExists(bucketName);
      return exists;
    } catch (err) {
      return false;
    }
  }
}
